package member

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"woo-server/coms/structs"
	"woo-server/coms/utils"
	"woo-server/models/api"
	"woo-server/models/db/member"
)

// 结构
type Service struct {
	*structs.Common
}

// 初始化
func NewGradeService(com *structs.Common) *Service {
	return &Service{com}
}

// 角色列表
func (s *Service) GetList(context *gin.Context) *api.ResultEntity {

	search := context.Query("search")
	page := structs.SetInt(context.Query("page"))
	pageSize := structs.SetInt(context.Query("pageSize"))
	Model := member.NewGrade(s.Common)
	list, total := Model.GetListAndTotal(search, page, pageSize)
	result := map[string]interface{}{"list": list, "total": total}
	return api.SuccessToJson(result, "会员等级列表获取成功!")
}

// 当前用户信息
func (s *Service) GetConfig(context *gin.Context) *api.ResultEntity {
	Model := member.NewGrade(s.Common)
	data := Model.GetConfig()
	return api.SuccessToJson(data, "获取配置成功!")
}

func (s *Service) PostSave(context *gin.Context) *api.ResultEntity {
	GradeName := context.PostForm("GradeName")
	if GradeName == "" {
		return api.Error("等级名称不能为空!")
	}
	Model := member.NewGrade(s.Common)
	GradeStatus := context.PostForm("GradeStatus")
	if GradeStatus != "" {
		Model.GradeStatus = uint(structs.SetInt(GradeStatus))
	} else {
		Model.GradeStatus = 1
	}
	Model.GradeName = GradeName
	Model.Weight = uint(structs.SetInt(context.PostForm("Weight")))
	Model.Describe = context.PostForm("Describe")
	Model.Upgrade = context.PostForm("Upgrade")
	Model.Discount = structs.SetFloat(context.PostForm("Discount"), 64)
	Model.GradeStatus = uint(structs.SetInt(context.PostForm("GradeStatus")))
	Model.FileId = uint64(structs.SetInt(context.PostForm("FileId")))
	GradeId := uint64(structs.SetInt(context.PostForm("GradeId")))
	fmt.Println("保存的数据:====", Model)
	var err error
	if GradeId == 0 {
		// 基础参数
		Model.SetCreateInfo(s.Claim.UserId)
		// 执行创建
		err = Model.Create()
	} else {
		Model.GradeId = GradeId
		Model.CreateUser = uint64(structs.SetInt(context.PostForm("CreateUser")))
		Model.SetUpdateInfo(s.Claim.UserId)
		err = Model.Save()

	}
	if err != nil {
		// 日志
		utils.LogError("新增/编辑等级报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("success")
}

func (s *Service) Delete(context *gin.Context) *api.ResultEntity {
	//context.Param()
	// 接收POST参数
	GradeId := context.PostForm("GradeId")
	// 校验参数
	if GradeId == "" {
		return api.Error("ID不能为空!")
	}
	if GradeId == "1" {
		api.Error("无法删除超级管理员")
	}
	// 实例化数据库
	Model := member.NewGrade(s.Common)
	// 执行删除
	Model.GradeId = uint64(structs.SetInt(GradeId))
	// 删除数据
	err := Model.Delete()
	if err != nil {
		utils.LogError("删除角色报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("删除成功")
}
